package com.ruoyi.web.utils;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.web.domain.AppUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * token工具类
 *
 * @author gong_da_kai
 * @version 1.0.0
 * @since 2021/12/27 2:45 下午
 */
public class TokenUtil {

    /**
     * 根据小程序用户创建loginUser对象
     *
     * @param user 小程序用户
     * @return {@link LoginUser}
     * @author gong_da_kai
     * @since 2021/12/24
     */
    public static LoginUser createLoginUser(AppUser user) {
        SysUser sysUser = transferAppUser(user);
        LoginUser loginUser = new LoginUser(sysUser, Constants.LOGIN_USER_TYPE_H5);

        // 保存鉴权信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        return loginUser;
    }

    /**
     * 将AppUser转换到SysUser
     *
     * @param appUser
     * @return {@link SysUser}
     * @since 2023/3/20 15:39
     */
    public static SysUser transferAppUser(AppUser appUser) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(appUser.getId());
        sysUser.setDeptId(appUser.getParentId());
        return sysUser;
    }
}
